<template>
    <div class="ListenBook">
        <div class="Nav">
            <van-icon class="arrow-left" color="#fff" size="20px" name="arrow-left" @click="goback" />
            <div class="title">{{ bookName }}</div>
            <van-icon class="ellipsis" color="#fff" size="20px" name="ellipsis" />
        </div>
        <!-- 内容 -->
        <div class="content" v-for="(item, index) in ListenBookDetail" :key="index">
            <!-- 封面 -->
            <div class="img-box">
                <img class="img-box" :src="item.cover" :alt="item.title" />
            </div>
            <!-- 书籍信息 -->
            <div class="BookInfo">
                <!-- 作者等信息 -->
                <div class="authorInfo">
                    <div class="author">作者: {{ item.author }}</div>
                    <div class="anchor">主播: {{ item.anchor }}</div>
                    <div class="pending">集数: {{ item.articleCount }}集</div>
                    <div class="price">每集价格: {{ item.price }}阅点</div>
                </div>
                <!-- 书籍简介 -->
                <div class="Book_introduction">
                    <div class="introduction-content">{{ item.description }}</div>
                </div>
            </div>
            <!-- 底部播放器 -->
            <div class="footPlayer">
                <!-- 进度条 -->
                <div class="progress" ref="progressBox" @touchstart="clickProgress">
                    <div class="line" :style="{ width: activeWidth + 'px' }"></div>
                    <div class="dot" :style="{ left: moveLeft + 'px' }" ref="move" @touchstart.stop="touchstart" @touchmove="touchmove" @touchend="touchend">
                        <div class="dotchild" :style="{ left: moveLeft + 'px' }"></div>
                    </div>
                    <!-- 进行时间 -->
                    <div class="timeing">{{ currentTime }}</div>
                    <!-- 总时间 -->
                    <div class="totalTime">{{ totalTime }}</div>
                </div>
                <!-- 目录上下播放定时 -->
                <div class="operationOne">
                    <audio ref="audio" @timeupdate="timeupdate" :src="audioList[activeIndex].downloadUrl" v-if="audioList !== null"></audio>
                    <van-icon name="bars" color="#fff" size="18px" />
                    <img src="../assets/images/shangyishou.png" @click="previous" />
                    <van-icon name="play-circle-o" color="#fff" size="60px" @click="playPause" v-show="runningStatus == false" />
                    <van-icon name="pause-circle-o" color="#fff" size="60px" @click="playPause" v-show="runningStatus == true" />
                    <img src="../assets/images/xiayishou.png" @click="next" />
                    <van-icon name="underway-o" color="#fff" size="18px" />
                </div>
                <!-- 加入书架 批量下载 评论 -->
                <div class="operationTwo">
                    <div class="operationTwo-item" @click="add" v-if="!addFlag">
                        <img src="../assets/images/shu.png" />
                        <div class="text">加入书架</div>
                    </div>
                    <div class="operationTwo-item" v-else>
                        <img src="../assets/images/shu_active.png" />
                        <div class="text black">已加入书架</div>
                    </div>
                    <div class="operationTwo-item">
                        <img src="../assets/images/xiazai.png" />
                        <div class="text">批量下载</div>
                    </div>
                    <div class="operationTwo-item">
                        <img src="../assets/images/31pinglun.png" />
                        <div class="text">评论</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Toast } from "vant";

export default {
    name: "ListenBook",
    data() {
        return {
            BookId: null,
            title: null,
            ListenBookDetail: null,
            // 书籍名字
            bookName: null,
            // 播放状态
            runningStatus: false,
            // 音频列表
            audioList: null,
            // 总时长
            totalTime: null,
            // 默认音频
            audioUrl: "https://easyreadfs.nosdn.127.net/b0b182224fd84df2a5a0ab5c30c1ce59.mp3",
            // 章节下标
            activeIndex: 0,
            duration: 0,
            // 总时间
            totalTime: 0,
            // 当前时间
            currentTime: "00:00",
            // 是否加入书架
            addFlag: false,
            // 需要的数据
            bookshelfData: {},
            // 音频dom对象
            audioDom: null,
            // 进度条总宽度
            progressWidth: 0,
            //激活进度条的宽度
            activeWidth: 0,
            //移动块的宽度
            moveWidth: 0,

            //移动块的left
            moveLeft: 0,
            //点击移动块的起始坐标
            initX: 0,
            //是否点击移动块
            isClickMove: false,
            //是否拖动移动块
            isMove: false,
            //进度条offsetLeft
            progressOffsetLeft: 0,
        };
    },
    created() {
        // 截取书籍id以及书籍标题
        this.BookId = this.$route.query.BookId;
        this.title = this.$route.query.title;

        // 获取听书详情
        this.getListenBook(this.BookId);
        // 音频地址
        this.getAudio();
        // 书籍是否已加入书架
        this.getAddFlag();
    },
    mounted() {
        // 获取音频dom对象
        setTimeout(() => {
            // 获取音频DOM对象
            this.getAudioDom();
            this.getProgressDom();

            // 进度条总宽度
            if (this.$refs.progressBox !== undefined) {
                this.progressWidth = this.$refs.progressBox[0].clientWidth;
                this.progressOffsetLeft = this.$refs.progressBox[0].offsetLeft;
            } else {
                this.getProgressDom();

                this.totalTime = this.formatTime(this.duration);
            }
            // 圆点宽度
            if (this.$refs.move !== undefined) {
                this.moveWidth = this.$refs.move[0].clientWidth;
            } else {
                this.totalTime = this.formatTime(this.duration);
            }
            this.moveLeft = -this.moveWidth / 2;

            // 获取音频总时长

            //
            if (this.audioDom !== null) {
                this.duration = this.audioDom.duration;
            } else {
                this.getAudioDom();
                this.totalTime = this.formatTime(this.duration);

                return;
            }

            this.totalTime = this.formatTime(this.duration);
            //
        }, 1000);
        setTimeout(() => {
            // 获取音频DOM对象
            // this.getAudioDom();
            this.totalTime = this.formatTime(this.duration);
        }, 1100);

        // 在update中执行一次
        this.$once("hook:updated", function () {
            this.getAudioDom();
            this.totalTime = this.formatTime(this.duration);
            this.progressWidth = this.$refs.progressBox[0].clientWidth;
            this.progressOffsetLeft = this.$refs.progressBox[0].offsetLeft;
            this.moveWidth = this.$refs.move[0].clientWidth;
        });
    },
    updated() {
        //
        this.totalTime = this.formatTime(this.duration);
    },
    methods: {
        // 获取音频DOM对象
        getAudioDom() {
            if (this.$refs.audio !== undefined) {
                this.audioDom = this.$refs.audio[0];
            } else {
                // this.getAudioDom();
            }
        },
        // 获取进度条dom
        getProgressDom() {
            if (this.$refs.progressBox !== undefined) {
                this.progressWidth = this.$refs.progressBox[0].clientWidth;
                this.progressOffsetLeft = this.$refs.progressBox[0].offsetLeft;
            } else {
                this.getProgressDom();
            }
        },
        // 获取听书详情
        getListenBook(BookId) {
            this.axios({
                methods: "get",
                url: "https://apis.netstart.cn/yunyuedu/ting/source.json?sourceUuid=" + BookId,
            })
                .then((res) => {
                    if (res.data.code == 0) {
                        this.ListenBookDetail = res.data.data.sources;
                        this.bookName = res.data.data.sources[0].title;
                        this.totalTime = res.data.data.sources[0].updateTime;

                        this.bookshelfData.BookId = res.data.data.sources[0].sourceUuid;
                        this.bookshelfData.title = res.data.data.sources[0].title;
                        this.bookshelfData.cover = res.data.data.sources[0].cover;
                    }
                })
                .catch((err) => {});
        },
        // 音频地址
        getAudio() {
            this.axios({
                methods: "get",
                url: "https://apis.netstart.cn/yunyuedu/ting/download.json",
            })
                .then((res) => {
                    if (res.data.code == 0) {
                        this.audioList = res.data.data.urls;

                        // for (let i = 0; i < this.audioList.length; i++) {
                        //     if (this.BookId == this.audioList[i].articleUuid) {
                        //
                        //     } else {
                        //
                        //     }
                        // }
                    }
                })
                .catch((err) => {});
        },
        // 音频进度发生改变
        timeupdate() {
            //
            // 当前播放时间
            let nowTime = this.audioDom.currentTime;
            // 当前播放时间/总时间
            let percent = nowTime / this.audioDom.duration;
            //
            // 百分比x进度条宽度
            let distance = percent * this.progressWidth;
            //
            // 进度条移动距离
            this.activeWidth = distance;
            // 圆点移动距离
            this.moveLeft = distance - this.moveWidth / 2;
            //
            this.currentTime = this.formatTime(nowTime);
        },
        //格式时间
        formatTime(duration) {
            //提取分钟、秒
            var minutes = Math.floor(duration / 60);
            minutes = minutes >= 10 ? minutes : `0${minutes}`;

            var seconds = Math.floor(duration % 60);
            seconds = seconds >= 10 ? seconds : `0${seconds}`;

            return `${minutes}:${seconds}`;
        },
        goback() {
            this.$router.back();
        },
        // 播放暂停
        playPause() {
            this.runningStatus = !this.runningStatus;

            // audioDom
            if (this.runningStatus) {
                if (this.audioDom !== null) {
                    this.audioDom.play();
                }
            } else {
                if (this.audioDom !== null) {
                    this.audioDom.pause();
                }
            }
        },
        // 下一首
        next() {
            this.activeIndex++;
            //
            setTimeout(() => {
                Toast("播放下一章");
                this.runningStatus = true;
                this.audioDom.play();
            }, 100);
        },
        // 上一章
        previous() {
            if (this.activeIndex > 0) {
                this.activeIndex--;
                setTimeout(() => {
                    Toast("播放上一章");
                    this.runningStatus = true;
                    this.audioDom.play();
                }, 100);
            } else {
                Toast("已经是第一章了!");
            }
        },

        // 添加书架
        add() {
            // 获取购物车的缓存数组(没有数据,则赋予一个空数组)
            let bookrackList = JSON.parse(localStorage.getItem("bookrackList")) || [];

            // 购物车有数据
            if (bookrackList.length > 0) {
                // 遍历书架数组
                for (let i = 0; i < bookrackList.length; i++) {
                    // 判断数组内书籍的id是否与当前需要加入的书籍id相同;
                    if (bookrackList[i].BookId == this.bookshelfData.BookId) {
                        // 相同就return
                        return;
                        //
                    }
                }
                // 不同就把当前项push进去
                bookrackList.push(this.bookshelfData);
                Toast.success("加入成功");
                this.addFlag = true;

                //
            } else {
                // 购物车没有数据 把当前书籍push进去

                bookrackList.push(this.bookshelfData);
                Toast.success("加入成功");
                this.addFlag = true;
            }

            // 存入本地
            localStorage.setItem("bookrackList", JSON.stringify(bookrackList));
        },

        // 判断当前书籍是否存在于书架列表中 存在则已加入表示为true
        getAddFlag() {
            // 获取书架列表
            let bookrackList = JSON.parse(localStorage.getItem("bookrackList")) || [];
            // 书架有书
            if (bookrackList.length > 0) {
                // 遍历书架 判断当前书籍id是否与书架中书id相同 相同即为已加入 为true

                for (let i = 0; i < bookrackList.length; i++) {
                    if (bookrackList[i].BookId == this.BookId) {
                        //
                        this.addFlag = true;
                        //
                        //
                    }
                }
                //
            } else {
                // 没有书籍已加入
                this.addFlag = false;
                //
            }
        },
        clickProgress(e) {
            //

            let left = e.changedTouches[0].pageX - this.progressOffsetLeft - this.moveWidth / 2;

            this.moveLeft = left;

            this.activeWidth = e.changedTouches[0].pageX - this.progressOffsetLeft;
            //设置音频播放时间
            let percent = this.activeWidth / this.progressWidth;
            let currentTime = percent * this.audioDom.duration;

            //
            this.audioDom.currentTime = currentTime;
        },

        touchstart(e) {
            this.initX = e.changedTouches[0].pageX;
            this.isClickMove = true;
        },

        touchmove(e) {
            this.isMove = true;

            //获取移动之后的坐标
            let x = e.changedTouches[0].pageX;

            //移动的差值
            let x0 = x - this.initX;

            //移动块的移动距离
            let left = this.moveLeft + x0;

            //控制移动块的移动范围
            let minLeft = -this.moveWidth / 2;
            let maxLeft = this.progressWidth - this.moveWidth / 2;

            left = left < minLeft ? minLeft : left > maxLeft ? maxLeft : left;

            this.moveLeft = left;

            this.activeWidth = left - minLeft;

            this.initX = x;

            if (this.isClickMove && this.isMove) {
                let percent = this.activeWidth / this.progressWidth;
                let currentTime = percent * this.audioDom.duration;
                this.currentTime = this.formatTime(currentTime);
            }
        },

        touchend() {
            let percent = this.activeWidth / this.progressWidth;
            let currentTime = percent * this.audioDom.duration;
            this.audioDom.currentTime = currentTime;
            this.isMove = false;
            this.isClickMove = false;
        },
    },
    watch: {
        // audioDom(a, b) {
        //
        //
        // },
    },
};
</script>

<style lang="less" scoped>
.ListenBook {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    // background-color: #6e6a67;
    &::after {
        content: "";
        // background-color: #6e6a67;
        // background-color: #a09c9c;
        background-color: #000;
        filter: blur(140px);
        position: fixed;
        display: inline-block;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        z-index: -1;
    }
    .content {
        width: 350px;
        // background-color: red;
        margin: 20px auto 0 auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        .footPlayer {
            width: 100%;
            // background-color: pink;
            margin-top: 75px;
            .operationTwo {
                display: flex;
                align-items: center;
                margin-top: 20px;
                .operationTwo-item {
                    text-align: center;
                    width: 33.333%;
                    .black {
                        color: #000 !important;
                    }
                    img {
                        width: 22px;
                        height: 22px;
                    }
                    .text {
                        color: #fff;
                        font-size: 12px;
                        margin-top: 5px;
                    }
                }
            }
            .operationOne {
                margin: 26px 0 0 0;
                display: flex;
                align-items: center;
                justify-content: space-around;
                img {
                    width: 40px;
                    height: 40px;
                }
            }
            .progress {
                width: 100%;
                height: 3px;
                background-color: #a9a8a4;
                position: relative;
                .timeing {
                    position: absolute;
                    top: 15px;
                    left: -7px;
                    font-size: 12px;
                    color: #fff;
                }
                .totalTime {
                    position: absolute;
                    top: 15px;
                    right: -7px;
                    font-size: 12px;
                    color: #fff;
                }

                .dot {
                    width: 18px;
                    height: 18px;
                    border-radius: 50%;
                    background-color: #fff;
                    position: absolute;
                    top: -7px;
                    left: -9px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    .dotchild {
                        width: 8px;
                        height: 8px;
                        border-radius: 50%;
                        background-color: red;
                    }
                }
                .line {
                    // content: "";
                    width: 0%;
                    height: 3px;
                    background-color: black;
                    display: inline-block;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }
        }
        .img-box {
            width: 100px;
            height: 130px;
            background-color: green;
        }
        .Book_introduction {
            .introduction-content {
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 5;
                overflow: hidden;
                color: #a6a2a1;
                line-height: 25px;
                margin-top: 20px;
            }
        }
        .BookInfo {
            width: 100%;
            margin: 30px auto 0 auto;
            height: 200px;
            .authorInfo {
                height: 50px;
                display: flex;
                flex-wrap: wrap;
                .author,
                .anchor,
                .pending,
                .price {
                    width: 50%;
                    text-align: center;
                    color: #fff;
                    line-height: 25px;
                }
            }
        }
    }

    .Nav {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        z-index: 999;
        .arrow-left {
            margin-left: 10px;
        }
        .ellipsis {
            margin-right: 15px;
        }
        .title {
            color: #fff;
            font-size: 16px;
        }
    }
}
</style>
